import React, { useEffect, useState } from 'react'
import './style.less'
import { Button, Form, Tag, Flex, Popconfirm } from 'antd'
import { EMPTYTEXT, hsHandleTableDateTime, message, usePage } from '@hs-admin/utils'
import { Link, Outlet, useLocation } from 'react-router-dom'
import { HsAdminTablePage, HsAdminForm, HsAdminSpin, HsAdminInput } from '@hs-admin/base-components'
import { HsAdminSelectTheme } from '@hs-admin/components'
import { dataItemStatus } from '@/utils/type'
import { getSettingDataItemList, publishDataItem } from '@/api/setting/item'
import classNames from 'classnames'
import PublishPlatform from '@/components/PublishPlatform'
import { getAllPlatform } from '@hs-server/api'

const DataItem: React.FC = () => {
  const location = useLocation()
  const [loading, setloading] = useState(true)
  const [keywords, setkeywords] = useState(undefined)
  const [showChildren, setshowChildren] = useState(false)
  const [allPlatform, setallPlatform] = useState([])

  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = usePage(callList)
  // 搜索和重置都会执行
  const handleSearch = async () => {
    resetPage()
  }
  const [form] = Form.useForm()
  const formItemOptions = [
    {
      name: 'keywords',
      FormItemColProps: {
        span: 6
      },
      slot: 'keywords'
    },
    {
      label: '所属主题',
      name: 'data_topic_id',
      slot: 'data_topic_id',
      FormItemColProps: {
        span: 6
      }
    },
    {
      label: '发布平台',
      name: 'platform_id__in',
      component: 'Cascader',
      componentProps: {
        options: allPlatform,
        onChange: (_value: any, selectedOptions: any) => {
          const find: any = allPlatform.find((item: any) => item.value === selectedOptions?.map((item: any) => item.value).join(','))
          //找到选中那一项 如果有children就不请求
          if (!find || !find?.children) {
            handleSearch()
          }
        },
        changeOnSelect: true
      },
      FormItemColProps: {
        span: 6
      }
    },
    {
      label: '发布状态',
      name: 'release_status',
      component: 'Select',
      componentProps: {
        options: dataItemStatus(),
        onChange: handleSearch
      },
      FormItemColProps: {
        span: 6
      }
    },
    {
      label: '数据特征',
      name: 'data_characteristics',
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '热门数据',
            value: '热门数据'
          },
          {
            label: '特色数据',
            value: '特色数据'
          }
        ],
        onChange: handleSearch
      },
      FormItemColProps: {
        span: 6
      }
    }
  ]

  const columns = [
    {
      title: '数据项名称',
      dataIndex: 'name'
    },
    {
      title: '数据项描述',
      dataIndex: 'description',
      width: 200,
      ellipsis: true
    },
    {
      title: '所属主题',
      dataIndex: 'data_topics',
      render: (_: any, record: any) => (
        <span>{record.data_topics?.length ? record.data_topics.map((item: any) => item.name).join(',') : EMPTYTEXT}</span>
      )
    },
    {
      title: '发布状态',
      dataIndex: 'release_status',
      render: (_: any, record: any) => (
        <div>{record.release_info?.release_status ? dataItemStatus(record.release_info.release_status) : EMPTYTEXT}</div>
      )
    },
    {
      title: '发布/下线时间',
      dataIndex: 'updated_at',
      render: (_: any, record: any) => (
        <span>{record.release_info?.updated_at ? hsHandleTableDateTime(record.release_info.updated_at) : EMPTYTEXT}</span>
      )
    },
    {
      title: '数据特征',
      dataIndex: 'data_characteristics',
      render: (_: any, record: { data_characteristics: string[] }) => (
        <>
          {record.data_characteristics?.map((tagKey) => (
            <Tag style={{ marginRight: '6px' }} bordered={false} color="processing" key={tagKey}>
              {tagKey}
            </Tag>
          ))}
          {!record.data_characteristics?.length && <span>{EMPTYTEXT}</span>}
        </>
      )
    },
    {
      title: '发布平台',
      dataIndex: 'release_info',
      render: (_: any, record: any) => (
        <span>
          {record.release_info?.platforms?.length ? record.release_info.platforms.map((item: { name: any }) => item.name)?.join(',') : EMPTYTEXT}
        </span>
      )
    },
    {
      title: '操作',
      dataIndex: 'actions',
      width: 200,
      fixed: 'right',
      render: (_: any, record: any) => {
        return actionCompute(record)
      }
    }
  ]
  const actionCompute = (record: any) => (
    <Flex gap={'middle'}>
      <Button type="link" size="small">
        <Link to={`/setting/dataItem/edit?id=${record.id || ''}`}>配置</Link>
      </Button>
      <Popconfirm
        description={
          <PublishPlatform
            type="Database"
            record={record}
            updateChecked={(checkedValue) => {
              record.checkedValue = checkedValue
            }}
          />
        }
        title=""
        trigger="click"
        icon=""
        onConfirm={() => {
          pushDataItem(record)
        }}>
        <Button type="link" size="small">
          发布
        </Button>
      </Popconfirm>
    </Flex>
  )
  const [data, setData] = useState<any[]>([])

  // 列表查询事件
  async function callList() {
    setloading(true)
    const fieldsValue = form.getFieldsValue()
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      ...fieldsValue,
      platform_id__in: fieldsValue.platform_id__in?.length ? fieldsValue.platform_id__in.at(-1) : null,
      keywords
    }
    const res = await getSettingDataItemList(params)
    setData(res.items ?? [])
    setloading(false)
    return res
  }
  // 发布
  const pushDataItem = async (record: any) => {
    setloading(true)
    publishDataItem({ id: record.id, platforms: record.checkedValue?.filter((item: string | any[]) => item.length) || [] })
      .then(() => {
        message.success('发布成功')
        callList()
      })
      .finally(() => {
        setloading(false)
      })
  }

  useEffect(() => {
    if (location.pathname.includes('/setting/dataItem/edit') || location.pathname.includes('/setting/dataItem/newEdit')) {
      setshowChildren(true)
    } else {
      setshowChildren(false)
    }
  }, [location])

  useEffect(() => {
    getAllPlatform({ use_for: 'data_item' }).then((res) => {
      setallPlatform(res)
    })
  }, [])

  return (
    <>
      <div className={classNames('dataItem', { hidden: showChildren })}>
        {loading && <HsAdminSpin />}
        <HsAdminForm form={form} formItemOptions={formItemOptions}>
          <div slot="data_topic_id">
            <HsAdminSelectTheme placeholder="请选择所属主题" onChange={handleSearch}></HsAdminSelectTheme>
          </div>
          <div slot="keywords">
            <HsAdminInput
              Search
              placeholder="请输入搜索内容"
              enterButton="搜索"
              onSearch={(value: React.SetStateAction<undefined>) => {
                setkeywords(value)
                handleSearch()
              }}
            />
          </div>
        </HsAdminForm>
        <HsAdminTablePage
          id="J-data-item-page"
          columns={columns}
          rowKey={(record: { id: any }) => record.id}
          dataSource={data}
          pagination={pagination}
          size="small"
        />
      </div>
      {showChildren && <Outlet />}
    </>
  )
}

export default DataItem
